package Test;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import org.apache.batik.dom.svg.SVGOMPathElement;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.gvt.GVTTreeRendererAdapter;
import org.apache.batik.swing.gvt.GVTTreeRendererEvent;
import org.apache.batik.swing.svg.GVTTreeBuilderAdapter;
import org.apache.batik.swing.svg.GVTTreeBuilderEvent;
import org.apache.batik.swing.svg.SVGDocumentLoaderAdapter;
import org.apache.batik.swing.svg.SVGDocumentLoaderEvent;
import org.w3c.dom.NodeList;

/**
 * @TODO Se borra nico?
 *
 * @author BIPiane
 */
public class SVGApplicationNico {

    public static void main(String[] args) {
        JFrame f = new JFrame("Batik");
        SVGApplicationNico app = new SVGApplicationNico(f);
        f.getContentPane().add(app.createComponents());
        f.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setSize(400, 400);
        f.setVisible(true);
    }
    JFrame frame;
    JButton button = new JButton("Load...");
    JLabel label = new JLabel();
    JSVGCanvas svgCanvas = new JSVGCanvas();

    public SVGApplicationNico(JFrame f) {
        frame = f;
    }

    public JComponent createComponents() {
        final JPanel panel = new JPanel(new BorderLayout());
        JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
        p.add(button);
        p.add(label);
        panel.add(p, BorderLayout.NORTH);
        panel.add(svgCanvas, BorderLayout.CENTER);

        // Set the button action.
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                JFileChooser fc = new JFileChooser(".");
                int choice = fc.showOpenDialog(panel);
                if (choice == JFileChooser.APPROVE_OPTION) {
                    File f = fc.getSelectedFile();
                    try {
                        svgCanvas.setURI(f.toURL().toString());
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        // Set the JSVGCanvas listeners.
        svgCanvas.addSVGDocumentLoaderListener(new SVGDocumentLoaderAdapter() {

            @Override
            public void documentLoadingStarted(SVGDocumentLoaderEvent e) {
                label.setText("Document Loading...");
            }

            @Override
            public void documentLoadingCompleted(SVGDocumentLoaderEvent e) {
                label.setText("Document Loaded.");
            }
        });

        svgCanvas.addGVTTreeBuilderListener(new GVTTreeBuilderAdapter() {

            @Override
            public void gvtBuildStarted(GVTTreeBuilderEvent e) {
                label.setText("Build Started...");
            }

            @Override
            public void gvtBuildCompleted(GVTTreeBuilderEvent e) {
                label.setText("Build Done.");
                frame.pack();
            }
        });

        svgCanvas.addGVTTreeRendererListener(new GVTTreeRendererAdapter() {

            @Override
            public void gvtRenderingPrepare(GVTTreeRendererEvent e) {
                label.setText("Rendering Started...");
            }

            @Override
            public void gvtRenderingCompleted(GVTTreeRendererEvent e) {
                label.setText("");
                SVGOMPathElement path = null;
                NodeList lista = svgCanvas.getSVGDocument().getElementsByTagName("path");
                for (int i = 0; i < lista.getLength(); i++) {
                    try {
                        String puntosSVG = lista.item(i).getAttributes().getNamedItem("d").getNodeValue();
                        path = (SVGOMPathElement) lista.item(i);
                        System.out.println();
                        System.out.println("----------------");
                        /**
                         * Muestra las transformaciones que se usan... muestra
                         * si se uso una c o l, etc
                         */
                        //                    System.out.println(path.getPathSegList().getNumberOfItems());
                        //                    for (int j = 0; j < path.getPathSegList().getNumberOfItems(); j++) {
                        //                        System.out.println(path.getPathSegList().getItem(j).getPathSegTypeAsLetter());
                        //                    }
                        System.out.println(path.getAttribute("d"));
                        crearDoc(path.getAttribute("d"));
                        svgCanvas.setURI(leerDoc().toURL().toString());

                        System.out.println("Datos del nuevo documento: ");
                        NodeList nodos = svgCanvas.getSVGDocument().getElementsByTagName("path");
                        //                    NodeList node = doc.getElementsByTagName("path");
                        //                    SVGOMPathElement pathAux = (SVGOMPathElement) node.item(0);
                        //                    System.out.println(pathAux.getAttribute("d"));
                        //                    System.out.println(path.getAnimatedPathData());
                        //                    System.out.println(path.getAnimatedPathData());


                        System.out.println(path.getAnimatedPathData());

                        for (int j = 0; j < 460; j = j + 30) {
                            System.out.print(path.getPointAtLength(j).getX() + " " + path.getPointAtLength(j).getY() + " ");

                        }
                        System.out.println();

                        //                    System.out.println(path.getPointAtLength(8).getX());
                        System.out.println("----------------");
                        //                    System.out.println("\nOriginal");
                        //                    System.out.println(puntosSVG);
                        //                    getPuntosRelativos(puntosSVG);
                        //                    System.out.println();
                        //                    getPuntosAbsolutos(puntosSVG);
                    } catch (MalformedURLException ex) {
                        Logger.getLogger(SVGApplicationNico.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });

        return panel;
    }

    private void getPuntosRelativos(String puntosSVG) {
        System.out.println("\ngetPuntosRelativos");
        String subNumero[] = puntosSVG.split(" ");
        String numeroJ = "m";
        for (int j = 0; j < subNumero.length; j++) {
            numeroJ = subNumero[j];
            if (Character.isLetter(numeroJ.charAt(0))) {
                numeroJ = numeroJ.substring(1);
            } else {
                if (Character.isLetter(numeroJ.charAt(numeroJ.length() - 1))) {
                    numeroJ = numeroJ.substring(0, numeroJ.length() - 1);
                }
            }
            System.out.print(numeroJ + " ");
        }
    }

    private void getPuntosAbsolutos(String puntosSVG) {
        System.out.println("\ngetPuntosAbsolutos");
        String subNumero[] = puntosSVG.split(" ");
        int px = 0;
        int py = 0;

        String resp = "M";
        for (int j = 0; j < subNumero.length; j++) {
            String numeroJ = subNumero[j];
            if (Character.isLetter(numeroJ.charAt(0))) {
                numeroJ = numeroJ.substring(1);
            } else {
                if (Character.isLetter(numeroJ.charAt(numeroJ.length() - 1))) {
                    numeroJ = numeroJ.substring(0, numeroJ.length() - 1);
                }
            }
            if (j % 2 == 0) {
                px += Integer.parseInt(numeroJ);
                resp = resp + px + " ";
            } else {
                py += Integer.parseInt(numeroJ);
                resp = resp + py + " ";
            }
        }
        System.out.print(resp);
    }

//    private SVGOMDocument crearDoc(SVGOMPathElement camino) {
//        DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
//        String svgNS = "http://www.w3.org/2000/svg";
//        Document doc = impl.createDocument(svgNS, "svg", null);
//
//// get the root element (the svg element)
//        Element svgRoot = doc.getDocumentElement();
//
//// set the width and height attribute on the svg root element
////        svgRoot.setAttributeNS(null, "width", "400");
////        svgRoot.setAttributeNS(null, "height", "450");
//
//// create the rectangle
////        Element path = doc.createElementNS(svgNS, "path");
////        path.setAttributeNS(null, "id", "camino");
////        path.setAttributeNS(null, "d", camino);
//        SVGOMPathElement path = (SVGOMPathElement) doc.importNode(camino, true);
//// attach the rectangle to the svg root element
//        svgRoot.appendChild(path);
//
//        return (SVGOMDocument) doc;
//    }
    public void crearDoc(String path) {
        try {
            File f = new File("d:/hola.svg");

            if (f.exists()) {
                f.delete();
            }
            FileWriter fichero = new FileWriter(f);
            PrintWriter pw = new PrintWriter(fichero);

            pw.println("<?xml version='1.0' standalone='no'?>");
            pw.println("<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 20010904//EN' 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'>");
            pw.println("<svg  version = '1.0' xmlns = 'http://www.w3.org/2000/svg'>");
            pw.println("<path d='" + path + "'/>");
            pw.println("</svg>");

            pw.close();
            fichero.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public File leerDoc() {
        File archivo = null;
        try {
            // Apertura del fichero y creacion de BufferedReader para poder
            // hacer una lectura comoda (disponer del metodo readLine()).
            archivo = new File("d:/aux.svg");
            // Lectura del fichero
        } catch (Exception e) {
            e.printStackTrace();
        }
        return archivo;
    }
}
